package com.wushijia.highconcurrency.semaphore;

import static java.lang.Thread.currentThread;

import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import lombok.SneakyThrows;

public class MySemaphore extends Semaphore {

  private final ConcurrentLinkedDeque<Thread> queue = new ConcurrentLinkedDeque<>();

  public MySemaphore(int permits, boolean fair) {
    super(permits, fair);
  }

  @SneakyThrows
  @Override
  public boolean tryAcquire(int permit) {
    final boolean acquired = super.tryAcquire(permit, 6, TimeUnit.SECONDS);
    if (acquired) {
      this.queue.add(currentThread());
    }
    return acquired;
  }

  @Override
  public void release(int permits) {
    if (!this.queue.contains(currentThread())) {
      return;
    }
    super.release(permits);
    this.queue.remove(currentThread());
  }
}
